package com.neusoft.neuiotms.dcom.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.KnowledgeType;
import com.neusoft.neuiotms.dcom.model.QKnowledgeType;
import com.neusoft.neuiotms.dcom.repository.CustomizedKnowledgeTypeRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * 
 * @author Liukq
 *
 */
public class CustomizedKnowledgeTypeRepositoryImpl extends AbstractRepository
implements CustomizedKnowledgeTypeRepository{

    @Override
    public Page<KnowledgeType> search(final Pageable pageable, final Searchable searchable) {
        final QKnowledgeType qKnowledgeType = QKnowledgeType.knowledgeType;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<KnowledgeType> query = this.query().selectFrom(qKnowledgeType);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QKnowledgeType qKnowledgeType = QKnowledgeType.knowledgeType;
        
        where.and(super.containsStr(qKnowledgeType.name, searchable, "name"));
        where.and(super.containsStr(qKnowledgeType.code, searchable, "code"));
        where.and(super.containsStr(qKnowledgeType.parent.name, searchable, "parentName"));
        final String[] codes = searchable.getStrArray("codes");
        if(codes!=null&&codes.length>0) {
            where.and(super.inStrings(qKnowledgeType.code,searchable,"codes"));
        }
        if(!StringUtils.isEmpty(searchable.getStrValue("parentId"))) {
            where.and(super.equalsLong(qKnowledgeType.parent.id,searchable,"parentId"));
        }
        if(!StringUtils.isEmpty(searchable.getStrValue("parentCode"))) {
            where.and(super.equalsStr(qKnowledgeType.parent.code,searchable,"parentCode"));
        }
        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        // TODO Auto-generated method stub
        return KnowledgeType.class;
    }

}
